package modules.ins.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.DateUtil;
import luxing.util.LoginUserUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import modules.arc.entity.Vehicle;
import modules.arc.service.VehicleService;
import modules.ins.entity.Insurance;
import modules.ins.entity.InsuranceKind;
import modules.ins.service.InsuranceService;
import modules.sys.entity.Dict;
import modules.sys.entity.Log;
import modules.sys.service.DictService;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/insuranceController")
public class InsuranceController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(InsuranceController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private InsuranceService insuranceService;
	@Autowired
	private VehicleService vehicleService;
	@Autowired
	private DictService dictService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/ins/insurance-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param insurance
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Insurance insurance, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Insurance.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, insurance, request.getParameterMap());
			cq.add();
			insuranceService.listByPage(cq, true);
			dataGrid.setFooter("premium,vavt,vehicle.sn:合计");
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("保险查询失败", e);
			throw new BusinessException("保险查询失败", e);
		}
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		return new ModelAndView("modules/ins/insurance-add");
	}

	/**
	 * 查看页面
	 * 
	 * @param insurance
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(Insurance insurance, HttpServletRequest request) {
		if (StringUtils.isNotBlank(insurance.getId())) {
			insurance = insuranceService.get(Insurance.class, insurance.getId());
			request.setAttribute("insurancePage", insurance);
		}
		return new ModelAndView("modules/ins/insurance-detail");
	}

	/**
	 * 商业险种
	 * 
	 * @return
	 */
	@RequestMapping(params = "insKindTab")
	public ModelAndView insKindTab(HttpServletRequest req) {
		List<InsuranceKind> insuranceKindList = new ArrayList<InsuranceKind>();
		List<Dict> dictList = dictService.listByGroupCode("insKind", LoginUserUtil.getLoginUser().getTenantId());
		for (Dict dict : dictList) {
			InsuranceKind insuranceKind = new InsuranceKind();
			insuranceKind.setInsKind(dict.getId());
			insuranceKind.setInsKindName(dict.getName());
			insuranceKindList.add(insuranceKind);
		}
		req.setAttribute("insuranceKindList", insuranceKindList);
		return new ModelAndView("modules/ins/insuranceKind-tab");
	}

	/**
	 * 投保险种
	 * 
	 * @return
	 */
	@RequestMapping(params = "insKindDetailTab")
	public ModelAndView insKindDetailTab(HttpServletRequest req) {
		Map<String, InsuranceKind> valueMap = new HashMap<String, InsuranceKind>();
		if (StringUtils.isNotBlank(req.getParameter("id"))) {
			Insurance insurance = insuranceService.get(Insurance.class, req.getParameter("id"));
			for (InsuranceKind insuranceKind : insurance.getInsuranceKindList()) {
				valueMap.put(insuranceKind.getInsKind(), insuranceKind);
			}
		}
		List<InsuranceKind> insuranceKindList = new ArrayList<InsuranceKind>();

		List<Dict> dictList = dictService.listByGroupCode("insKind", LoginUserUtil.getLoginUser().getTenantId());
		for (Dict dict : dictList) {
			InsuranceKind insuranceKind = new InsuranceKind();
			insuranceKind.setInsKind(dict.getId());
			insuranceKind.setInsKindName(dict.getName());
			if (valueMap.get(dict.getId()) != null) {
				insuranceKind.setTenantId(valueMap.get(dict.getId()).getTenantId());
				insuranceKind.setInsAmount(valueMap.get(dict.getId()).getInsAmount());
				insuranceKind.setPremium(valueMap.get(dict.getId()).getPremium());
			}
			insuranceKindList.add(insuranceKind);
		}
		req.setAttribute("insuranceKindList", insuranceKindList);
		return new ModelAndView("modules/ins/insuranceKindDetail-tab");
	}

	/**
	 * 增加
	 * 
	 * @param insurance
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(Insurance insurance, HttpServletRequest request) {
		String msg = null;
		try {
			// 状态
			if (insurance.getEndDate().getTime() > new Date().getTime()) {
				insurance.setStatus(Insurance.STATUS_ENABLE);
			} else {
				insurance.setStatus(Insurance.STATUS_DISABLE);
			}
			insurance.setWarn(Insurance.WARN_NORMAL);
			// 如果责任金额和保费为空
			Iterator<InsuranceKind> iterator = insurance.getInsuranceKindList().iterator();
			while (iterator.hasNext()) {
				InsuranceKind insuranceKind = iterator.next();
				if (insuranceKind.getInsAmount() == null && insuranceKind.getPremium() == null) {
					iterator.remove();
				} else {
					insuranceKind.setInsurance(insurance);
				}
			}
			// bean校验
			msg = ValidatorUtil.validate(insurance);
			if (StringUtils.isNotBlank(msg)) {
				return Result.error(msg);
			}
			insuranceService.save(insurance);
			msg = "车辆\"" + insurance.getVehicle().getPlateNumber() + "\"保险增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "车辆\"" + insurance.getVehicle().getPlateNumber() + "\"保险增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(Insurance insurance, HttpServletRequest request) {
		String msg = null;
		try {
			insurance = insuranceService.get(Insurance.class, insurance.getId());
			insuranceService.delete(insurance);
			msg = "车辆\"" + insurance.getVehicle().getPlateNumber() + "\"保险删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "车辆\"" + insurance.getVehicle().getPlateNumber() + "\"保险删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 车辆 change
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "vehicleChange")
	@ResponseBody
	public Result vehicleChange(HttpServletRequest req) {
		Result result = new Result();
		String vehicleId = req.getParameter("vehicleId");
		String type = req.getParameter("type");
		Map<String, Object> attributes = new HashMap<String, Object>();
		String startDate = DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
		Vehicle vehicle = vehicleService.get(Vehicle.class, vehicleId);
		List<Insurance> list = insuranceService.listByVehicleAndType(vehicleId, type);
		if (CollectionUtils.isNotEmpty(list)) {
			Insurance insurance = list.get(0);
			Calendar startCal = DateUtil.getCalendar(insurance.getEndDate());
			startCal.add(Calendar.DATE, 1);
			startDate = DateUtil.dateToStr(startCal.getTime(), "yyyy-MM-dd");
		} else if (vehicle.getRegisterDate() != null) {
			startDate = DateUtil.dateToStr(vehicle.getRegisterDate(), "yyyy-MM-dd");
		}
		Calendar endCal = DateUtil.getCalendar(DateUtil.strToDate(startDate, "yyyy-MM-dd"));
		endCal.add(Calendar.YEAR, 1);
		endCal.add(Calendar.DATE, -1);
		String endDate = DateUtil.dateToStr(endCal.getTime(), "yyyy-MM-dd");
		attributes.put("startDate", startDate);
		attributes.put("endDate", endDate);
		result.setAttributes(attributes);
		return result;
	}

	/**
	 * 类型 change
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "typeChange")
	@ResponseBody
	public Result typeChange(HttpServletRequest req) {
		Result result = new Result();
		String vehicleId = req.getParameter("vehicleId");
		String type = req.getParameter("type");
		if (StringUtils.isNotBlank(vehicleId) && StringUtils.isNotBlank(type)) {
			Map<String, Object> attributes = new HashMap<String, Object>();
			String startDate = DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
			Vehicle vehicle = vehicleService.get(Vehicle.class, vehicleId);
			List<Insurance> list = insuranceService.listByVehicleAndType(vehicleId, type);
			if (CollectionUtils.isNotEmpty(list)) {
				Insurance insurance = list.get(0);
				Calendar startCal = DateUtil.getCalendar(insurance.getEndDate());
				startCal.add(Calendar.DATE, 1);
				startDate = DateUtil.dateToStr(startCal.getTime(), "yyyy-MM-dd");
			} else if (vehicle.getRegisterDate() != null) {
				startDate = DateUtil.dateToStr(vehicle.getRegisterDate(), "yyyy-MM-dd");
			}
			Calendar endCal = DateUtil.getCalendar(DateUtil.strToDate(startDate, "yyyy-MM-dd"));
			endCal.add(Calendar.YEAR, 1);
			endCal.add(Calendar.DATE, -1);
			String endDate = DateUtil.dateToStr(endCal.getTime(), "yyyy-MM-dd");
			attributes.put("startDate", startDate);
			attributes.put("endDate", endDate);
			result.setAttributes(attributes);
		}
		return result;
	}

	/**
	 * 时间 change
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "startDateChange")
	@ResponseBody
	public Result startDateChange(HttpServletRequest req) {
		Result result = new Result();
		String startDate = req.getParameter("startDate");
		if (StringUtils.isNotBlank(startDate)) {
			Map<String, Object> attributes = new HashMap<String, Object>();
			Calendar endCal = DateUtil.getCalendar(DateUtil.strToDate(startDate, "yyyy-MM-dd"));
			endCal.add(Calendar.YEAR, 1);
			endCal.add(Calendar.DATE, -1);
			String endDate = DateUtil.dateToStr(endCal.getTime(), "yyyy-MM-dd");
			attributes.put("endDate", endDate);
			result.setAttributes(attributes);
		}
		return result;
	}
}
